package com.zzxy.spring34.aspect;

import com.zzxy.spring34.service.ITeacherService;
import com.zzxy.spring34.service.impl.TeacherServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyBeanFactoryCglib {
    public static ITeacherService createTeacherService(){
        ITeacherService  teacherService= new TeacherServiceImpl();
        MyAspect aspect= new MyAspect();
//        ITeacherService proxy = (ITeacherService) Proxy.newProxyInstance(MyBeanFactoryCglib.class.getClassLoader(), teacherService.getClass().getInterfaces(),
//                new InvocationHandler() {
//                    @Override
//                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                        aspect.before();
//                        Object obj = method.invoke(teacherService, args);
//                        aspect.after();
//                        return obj;
//                    }
//                });
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(teacherService.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                aspect.before();
                Object obj = methodProxy.invokeSuper(proxy,args);
                aspect.after();

                return obj;
            }
        });
        TeacherServiceImpl proxy = (TeacherServiceImpl) enhancer.create();
        return proxy;

    }



//            (MyBeanFactory.class.getClassLoader(),teacherService.getclass().getInterfaces(),);
}
